package com.eatme.web.app.article.service.impl;

import com.eatme.web.app.article.repository.ArticleRepository;
import com.eatme.web.app.article.entity.Article;
import com.eatme.web.app.article.job.PublishArticleJob;
import com.eatme.web.app.article.service.ArticleService;
import com.eatme.web.common.vo.AppResponse;
import com.eatme.web.sys.quartz.service.IScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private IScheduleService scheduleService;

    private static final Logger LOG = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    ArticleRepository articleRepository;

    @Override
    public AppResponse addArticle(com.eatme.web.app.article.entity.Article article) {
        article = articleRepository.save(article);
//        int i = articleDao.addArticle(article);
        if (!Objects.isNull(article.getPublish_time())) {
            handleScheduledAfter(article);
        }
        return AppResponse.ok();
    }

    @Override
    public AppResponse editArticle(com.eatme.web.app.article.entity.Article article) {
        Optional<com.eatme.web.app.article.entity.Article> optionalArticle = articleRepository.findById(article.getId());
        com.eatme.web.app.article.entity.Article article1 = optionalArticle.get();
        article1.setContent(article.getContent());
        article1.setTitle(article.getTitle());
        article1.setStatus(1);
        article1 = articleRepository.save(article1);
        return AppResponse.ok();
    }

    @Override
    public AppResponse findList(com.eatme.web.app.article.entity.Article article,Pageable pageable) {
        // ExampleMatcher matcher = ExampleMatcher.matching();
        article.setStatus(1);
        Example<com.eatme.web.app.article.entity.Article> example = Example.of(article);
        Page<com.eatme.web.app.article.entity.Article> page = articleRepository.findAll(example,pageable);
        Map<String,Object> returnData = new HashMap<>();
        List<com.eatme.web.app.article.entity.Article> data = page.getContent();
        returnData.put("count",page.getTotalElements());
        returnData.put("list",data);
        return AppResponse.ok().data(returnData);
    }

    @Override
    public AppResponse getDetail(Integer id) {
        Optional<com.eatme.web.app.article.entity.Article> article = articleRepository.findById(id);
        return AppResponse.ok().data(Optional.of(article));
    }

    @Override
    @Transactional
    public AppResponse delete(Integer id) {
        int i = articleRepository.updateArticleStatusById(id);
        return AppResponse.ok();
    }

    @Override
    public AppResponse updateSort(Integer initRanking, Integer finalRanking) {
        List<Article> articles =  articleRepository.findArticlesByRankingIn(Arrays.asList(initRanking,finalRanking));
        articles.stream().forEach(article -> {
            if (article.getRanking().equals(initRanking)) {
                article.setRanking(finalRanking);
            }else {
                article.setRanking(initRanking);
            }
            articleRepository.save(article);
        });
        return AppResponse.ok();
    }

    @Override
    public boolean publishArticle(Integer id) {
        LOG.debug("定时任务: {} 开始执行", id);
        com.eatme.web.app.article.entity.Article article = articleRepository.getReferenceById(id);
        article.setPublish(true);
        article = articleRepository.save(article);
        return true;
    }

    @Override
    public AppResponse query(com.eatme.web.app.article.entity.Article article,Pageable pageable) {
        article.setStatus(1);
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<com.eatme.web.app.article.entity.Article> example = Example.of(article,matcher);
        Long count = articleRepository.count(example);
        Page<com.eatme.web.app.article.entity.Article> page = articleRepository.findAll(example,pageable);
        Map<String,Object> returnData = new HashMap<>();
        List<com.eatme.web.app.article.entity.Article> data = page.getContent();
        returnData.put("count",count);
        returnData.put("data",data);
        return AppResponse.ok().data(returnData);
    }

    private void handleScheduledAfter(com.eatme.web.app.article.entity.Article article) {
        // 文章已经保存为草稿了，并且拿到了文章 ID
        // 调用定时任务
        String jobName = scheduleService.scheduleFixTimeJob(PublishArticleJob.class, article.getPublish_time(), article.getId());
        LOG.debug("定时任务: {} 开始执行", jobName);
    }
}
